<!-- 车辆借调 -->
<template>
  <div class="page-container">
    <div class="quick-search">
      <div
        v-for="item in quickSearchData"
        :key="item.key"
        class="quick-search-item"
        :class="[item.checked ? 'quick-search-item-checked' : '']"
        @click="quickSearchClick(item)"
      >
        <div class="quick-search-item-label">
          {{ item.label }}
          <a-tooltip content="所有借调单的付款费用金额之和" position="top" mini v-if="item.key == 1">
            <icon-question-circle />
          </a-tooltip>
          <a-tooltip content="所有借调单的收款费用金额之和" position="top" mini v-if="item.key == 2">
            <icon-question-circle />
          </a-tooltip>
        </div>
        <div class="quick-search-item-value" :class="[item.checked ? 'quick-search-item-value-checked' : '']">
          {{ item.value + (item.key == 1 || item.key == 2 ? '元' : '单') }}
        </div>
      </div>
    </div>
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" @reset="handleReset" />
    <table-index :table="table" @loadData="loadData">
      <template #carInfo="{ record }">
        <div>{{ record.licenseNo }}</div>
        <div>{{ record.modelName }}</div>
      </template>
    </table-index>
  </div>

  <!-- 归还 -->
  <return-car ref="return_car" @ok="loadData" />
  <!-- 取车 -->
  <take-car ref="take_car" @ok="loadData" />
  <!-- 添加费用 -->
  <car-add-cost-modal ref="carAddModalRef" @ok="onOKAddfee"
/></template>

<script setup name="CarInspectList">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { usePageDict } from '@/hooks/useDict'
  import { getCarTransferList, getStatistics } from '@/api/asset/carTransfer'
  import ReturnCar from './compoents/returnCar.vue'
  import TakeCar from './compoents/takeCar.vue'
  import carAddCostModal from '../../car/car-manage/components/car-add-cost-modal.vue'
  import useNavigate from '@/hooks/useNavigate'
  import dayjs from 'dayjs'
  import { useRoute } from 'vue-router'
  import { addFee } from '@/api/asset/carTransfer'
  const route = useRoute()
  const query = route.query
  const { navigateTo } = useNavigate()

  const dict = usePageDict('carTransferDict')
  // 查询条件
  const searchList = computed(() => {
    return [
      {
        label: '调车单号',
        prop: 'code',
        type: 'a-input',
      },
      {
        label: '车牌号',
        prop: 'licenseNo',
        type: 'a-input',
      },
      {
        label: '调入后车辆归属门店',
        prop: 'siteId',
        type: 'remote-select',
        attrs: {
          type: 'site_listBystaff',
        },
      },
      { label: '借调类型', prop: 'typeList', type: 'a-select', options: dict.typeEnum, attrs: { multiple: true } },
      {
        label: '借调开始时间',
        prop: 'startDateRange',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:23:59'],
          },
        },
        change: (value = []) => {
          queryParam.startTimeStart = value[0]
          queryParam.startTimeEnd = value[1]
        },
      },
      {
        label: '借调结束时间',
        prop: 'endDateRange',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:23:59'],
          },
        },
        change: (value = []) => {
          queryParam.endTimeStart = value[0]
          queryParam.endTimeEnd = value[1]
        },
      },
      {
        label: '被借调同行',
        prop: 'sourceId',
        type: 'remote-select',
        attrs: {
          type: 'transferCompany',
        },
      },
      { label: '借调状态', prop: 'statusList', type: 'a-select', options: dict.statusEnum, attrs: { multiple: true } },
      {
        label: '创建人',
        prop: 'staffIdtest',
        type: 'remote-select',
        attrs: {
          type: 'staff_authOrg',
        },
        change: (_, option = {}) => {
          queryParam.staffId = option.userId
        },
      },
      {
        label: '车型',
        prop: 'modelId',
        type: 'remote-select',
        attrs: {
          type: 'car_model_tenantList',
        },
      },
    ]
  })

  const quickSearchData = ref([
    {
      key: 1,
      label: '付款费用',
      value: 0,
      checked: false,
    },
    {
      key: 2,
      label: '收款费用',
      value: 0,
      checked: false,
    },
    {
      key: 3,
      label: '即将结束',
      value: 0,
      checked: false,
    },
    {
      key: 4,
      label: '超时未还',
      value: 0,
      checked: false,
    },
  ])

  const queryParam = reactive({
    startDateRange: [],
    endDateRange: [],
  })
  const carAddModalRef = ref(null)

  // table 配置
  const table = useTable({
    columns: [
      { title: '调车单号', dataIndex: 'code', width: 160, fixed: 'left' },
      { title: '车辆信息', slotName: 'carInfo' },
      { title: '调入后车辆归属门店', width: 160, dataIndex: 'siteName' },
      { title: '借调类型', dataIndex: 'typeName', width: 100 },
      { title: '借调开始时间', dataIndex: 'startTime', width: 170 },
      { title: '借调结束时间', dataIndex: 'endTime', width: 170 },
      { title: '租期', dataIndex: 'rentDays' },
      { title: '被调车的门店或同行', width: 160, dataIndex: 'sourceName' },
      {
        title: '费用金额',
        dataIndex: 'amount',
        unit: '元',
        titleTooltipContent: '借调单下收款 - 付款的金额',
      },
      { title: '借调状态', dataIndex: 'statusName', width: 100 },
      { title: '创建人', dataIndex: 'createUserName' },
      { title: '操作时间', dataIndex: 'createTime', width: 170 },
    ],
    operates: [
      {
        label: '详情',
        permission: 'svms:asstes:operation:car-transfer.detail',
        method: (record) => {
          navigateTo(
            `/car-transfer/detail/${record.id}?id=${record.id}&carId=${record.carId}&type=${record.type}&carCode=${record.code}&tab=1`,
            `${record.licenseNo}-借调详情`
          )
        },
      },
      {
        label: '添加费用',
        permission: 'svms:asstes:operation:car-transfer.addFee',
        method: (record) => {
          carAddModalRef.value.open(record)
        },
      },
      {
        label: '结算/修改费用',
        permission: 'svms:asstes:operation:car-transfer.edit',
        span: 2,
        method: (record) => {
          navigateTo(
            `/car-transfer/detail/${record.id}?id=${record.id}&carId=${record.carId}&carCode=${record.code}&type=${record.type}&tab=2`,
            `${record.licenseNo}-借调详情`
          )
        },
      },
      {
        label: '归还',
        permission: 'svms:asstes:operation:car-transfer.return',
        // 状态为【借入-借调中】
        show: (record) => record.status == 1 && record.type == 1,
        method: (record) => {
          handleReturn(record)
        },
      },
      {
        label: '取车',
        permission: 'svms:asstes:operation:car-transfer.get',
        // 状态为【借出-借调中】
        show: (record) => record.status == 1 && record.type == 2,
        method: (record) => {
          handleTake(record)
        },
      },
      {
        label: '操作记录',
        permission: 'svms:asstes:operation:car-transfer.operaterecords',
        method: (record) => {
          navigateTo(
            `/car-transfer/detail/${record.id}?id=${record.id}&carId=${record.carId}&type=${record.type}&carCode=${record.code}&tab=3`,
            `${record.licenseNo}-操作记录`
          )
        },
      },
    ],
    buttons: [
      {
        type: 'primary',
        icon: 'plus',
        label: '新增',
        permission: 'svms:asstes:operation:car-transfer.create',
        method: () => {
          navigateTo('/car-transfer/create')
        },
      },
    ],
  })
  // 列表接口调用
  const loadData = useFetchTableDataApi(table, queryParam, getCarTransferList)

  const onOKAddfee = (formRef, list, costInfo) => {
    formRef.value.validate((valid) => {
      if (!valid) {
        addFee({ id: costInfo.id, feeList: list }).then((res) => {
          loadData()
          getStatisticsApi()
          carAddModalRef.value.close()
        })
      }
    })
  }

  // 重置
  const handleReset = () => {
    quickSearchData.value.forEach((item) => {
      item.checked = false
    })
  }
  //快捷查询
  const quickSearchClick = (item) => {
    queryParam.startDateRange = []
    queryParam.endDateRange = []
    queryParam.code = undefined
    queryParam.licenseNo = undefined
    queryParam.siteId = undefined
    queryParam.type = undefined
    queryParam.startTimeStart = undefined
    queryParam.startTimeEnd = undefined
    queryParam.endTimeStart = undefined
    queryParam.endTimeEnd = undefined
    queryParam.sourceType = undefined
    queryParam.sourceId = undefined
    queryParam.status = undefined
    queryParam.staffId = undefined
    queryParam.modelId = undefined
    queryParam.typeList = []
    queryParam.statusList = []
    quickSearchData.value.forEach((ele) => {
      if (ele.key == item.key) {
        ele.checked = true
      } else {
        ele.checked = false
      }
    })
    if (item.key == 1) {
      queryParam.typeList = [2]
    }
    if (item.key == 2) {
      queryParam.typeList = [0, 1]
    }
    if (item.key == 3) {
      queryParam.statusList = [1]
      let startTime = dayjs().format('YYYY-MM-DD 00:00:00')
      let endTime = dayjs().add(3, 'days').format('YYYY-MM-DD 23:59:59')
      queryParam.endDateRange[0] = startTime
      queryParam.endDateRange[1] = endTime
      queryParam.endTimeStart = startTime
      queryParam.endTimeEnd = endTime
    }
    if (item.key == 4) {
      queryParam.statusList = [1]
      let startTime = dayjs().subtract(30, 'days').format('YYYY-MM-DD 00:00:00')
      let endTime = dayjs().format('YYYY-MM-DD 23:59:59')
      queryParam.endDateRange[0] = startTime
      queryParam.endDateRange[1] = endTime
      queryParam.endTimeStart = startTime
      queryParam.endTimeEnd = endTime
    }
    loadData()
  }

  // 还车
  const return_car = ref(null)
  const handleReturn = (record) => {
    return_car.value.show(record)
  }

  // 取车
  const take_car = ref(null)
  const handleTake = (record) => {
    take_car.value.show(record)
  }

  // 获取数据统计
  const getStatisticsApi = () => {
    getStatistics({}).then((res) => {
      if (res.code == 200) {
        console.log(res)
        const result = res.result
        quickSearchData.value.forEach((item) => {
          if (item.key == 1) {
            item.value = result.borrowAmount
          }
          if (item.key == 2) {
            item.value = result.lendAmount
          }
          if (item.key == 3) {
            item.value = result.soonEnd
          }
          if (item.key == 4) {
            item.value = result.timeoutOverdue
          }
        })
      }
    })
  }

  if (query.code) {
    queryParam.code = query.code
    loadData()
  }

  onMounted(() => {
    loadData()
    getStatisticsApi()
  })
</script>

<style lang="less" scoped>
  .quick-search {
    display: flex;
    margin-bottom: 20px;
  }
  .quick-search-item {
    width: 25%;
    height: 62px;
    padding: 9px 0 9px 16px;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #e5e8ef;
  }
  .quick-search-item:hover {
    transform: scale(1.1);
    transition: transform 0.3s;
    position: relative;
    z-index: 999;
  }
  .quick-search-item-checked {
    background: #e8f3ff;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #1890ff;
  }
  .quick-search-item:nth-of-type(n + 2) {
    margin-left: 20px;
  }
  .quick-search-item-label {
    font-size: 12px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #4e5969;
  }
  .quick-search-item-value {
    font-size: 20px;
    font-family: PingFang SC-Semibold, PingFang SC;
    font-weight: 600;
    color: #1d2129;
  }
  .quick-search-item-value-checked {
    color: #1890ff;
  }
</style>
